package fr.liglab.adele.icasa.rooms;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;

import fr.liglab.adele.icasa.device.DeviceListener;
import fr.liglab.adele.icasa.device.light.DimmerLight;
import fr.liglab.adele.icasa.device.light.Photometer;
import fr.liglab.adele.icasa.device.temperature.Cooler;
import fr.liglab.adele.icasa.device.temperature.Heater;
import fr.liglab.adele.icasa.device.temperature.Thermometer;
import fr.liglab.adele.icasa.environment.SimulatedEnvironment;
import fr.liglab.adele.icasa.environment.SimulatedEnvironmentManager;
import fr.liglab.adele.icasa.interfaces.IKitchen;

@Component
@Provides
public class Kitchen implements DeviceListener, IKitchen {

	@Requires
	Heater heater;
	
	@Requires
	Cooler cooler;
	
	@Requires
	Thermometer thermometer;
	
	@Requires(filter="(environment.id=envKitchen)")
	SimulatedEnvironment env;
	
	@Requires
	SimulatedEnvironmentManager env_manager;
	
	double target_temperature;
	
	@Validate
	public void starting(){
		env_manager.bindDeviceToEnvironment("heater", "envKitchen");
		env_manager.bindDeviceToEnvironment("cooler", "envKitchen");
		env_manager.bindDeviceToEnvironment("thermometer", "envKitchen");
		
		env.setProperty(SimulatedEnvironment.VOLUME, 2.0d);
		env.setProperty(SimulatedEnvironment.TEMPERATURE, 0.1d);
        
        thermometer.addListener(this);
		
        System.out.println(" ---------> Kichen ACTIVE <--------- " );  
	}
	
	@Invalidate
	public void stopping(){
		System.out.println( " ---------> Kichen INACTIVE <--------- " ); 
	}
	
	public void notifyDeviceEvent() {
		NumberFormat formatter = new DecimalFormat("#0.00");
		double currentTemperature = thermometer.getTemperature();
		double temp_heater=heater.getPowerLevel();
		double temp_cooler=cooler.getPowerLevel();

		System.out.println(
							" <Kichen> current temperature=" + formatter.format(currentTemperature)	+ " target=" + formatter.format(target_temperature) 
							+ " heater_power="+formatter.format(temp_heater)+ " cooler_power="+formatter.format(temp_cooler));
		
		if (currentTemperature < target_temperature) { 
			if (temp_heater<=0.9)
				heater.setPowerLevel(temp_heater + 0.1);
			if (temp_cooler>=0.1)
				cooler.setPowerLevel(temp_cooler - 0.1);
		} else if (currentTemperature > target_temperature) {
			if (temp_cooler<=0.9)
				cooler.setPowerLevel(temp_cooler + 0.1);
			if (temp_heater>=0.1)
				heater.setPowerLevel(temp_heater - 0.1);
		}else {
			System.out.println(" <Kichen> heater stay in the same temperature");
		}	
	}

	public void setTargetTemperature(double newvalue){
		target_temperature=newvalue;
	}

	
}
